package com.rest.demo.jdbcdemo.dao.impl;

import com.rest.demo.jdbcdemo.dao.IUserDao;
import com.rest.demo.jdbcdemo.entity.UserPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Administrator
 * @decription
 * @Date 2017-11-14 14:33
 */
@Repository
public class UserDaoImpl implements IUserDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<UserPo> finaAllUser() {
        List<UserPo> userPoList = jdbcTemplate.query("select * from t_user",new Object[]{},new BeanPropertyRowMapper(UserPo.class));
        if(userPoList.isEmpty()) {
            return null;
        }
        return userPoList;
    }

    @Override
    public UserPo findUserById(Integer id) {
        List<UserPo> userPos = jdbcTemplate.query("select * from t_user where user_id=?",new Object[]{id},new BeanPropertyRowMapper(UserPo.class));
        if(userPos.isEmpty()) {
            return null;
        }
        UserPo userPo = userPos.get(0);
        return userPo;
    }

    @Override
    public int saveUser(UserPo userPo) {
        return jdbcTemplate.update("insert into t_user(user_name) value(?)",userPo.getUserName());
    }

    @Override
    public int updateUser(UserPo userPo) {
        return jdbcTemplate.update("update t_user set user_name = ? where user_id = ?",userPo.getUserName(),userPo.getUserId());
    }

    @Override
    public int deleteUser(Integer id) {
        return jdbcTemplate.update("delete from t_user where user_id=?",id);
    }
}
